<?php

namespace app\admin\controller;

use app\common\controller\BasicAdmin;;

use app\common\model\CourseAttendanceModel;
use app\common\model\CourseCateModel;
use app\common\model\CourseModel;
use app\common\model\SchoolClassModel;
use app\common\model\SchoolGradeModel;
use app\common\model\SchoolModel;
use app\common\model\UserModel;
use app\common\model\UserTimesModel;
use app\common\traits\SelectPage;
use think\facade\Request;
use think\Model;
use think\db;

/**
 * Class CourseInterest
 * 兴趣课
 */
class CourseInterest extends BasicAdmin
{
    use SelectPage;

    protected $model = 'CourseModel';

    /**
     * 课程管理
     */
    public function index(){
        $this->title = '课程管理';
        $this->_query($this->model)
            ->where('type',2)
            ->where(function ($db){
                if($this->request->has('status','get') && !empty($this->request->get('status'))){
                    $status = $this->request->get('status');
                    $db->where('status', $status);
                }
                if($this->request->has('cate_id','get') && !empty($this->request->get('cate_id'))){
                    $cate_id = $this->request->get('cate_id');
                    $db->where('cate_id', $cate_id);
                }
                if($this->request->has('school_id','get') && !empty($this->request->get('school_id'))){
                    $school_id = $this->request->get('school_id');
                    $db->where('school_id', $school_id);
                }
            })
            ->like('name,title')
            ->with(['coursecate','school','schoolgrade','schoolclass','teacher'])
            ->append(['sign_totals'])
            ->page();
    }

    /**
     * 添加
     */
    public function add()
    {
        $this->title = '添加';
        return $this->_form($this->model, 'form');
    }

    public function _add_form_filter(&$data)
    {
        if ($this->request->isPost()) {
            $this->alterInfo($data);
        }
    }
    
    /**
     * 添加
     */
    public function add_user_time()
    {

        if (Request::instance()->isGet()){
            $this->title = '添加学生报名此课程';
            return $this->_form($this->model, 'user_times');
        }else{
            return $this->addUserTime();
        }

    }

    public function addUserTime(){

        $user = UserModel::get(input('user_id'));
        if(empty($user['realname'])){
            $this->error('真实姓名未填，请去个人中心修改信息','',400);
        }

        $course_id = input('id');
        $course = CourseModel::where('id',$course_id)->find();
        $teacher_id = $course['teacher_id'];
        $time = $course['time'];

        if(!empty($course['school_id']) && $course['school_id']!=$user['school_id']){
            $this->error('学生绑定学校不符','',400);
        }

        if(!empty($course['begin_choose_time'])&&time()<strtotime($course['begin_choose_time'])){
            $this->error('未到选课开始时间:'.$course['begin_choose_time'],'',400);
        }
        if(!empty($course['end_choose_time'])&&time()>strtotime($course['end_choose_time'])){
            $this->error('已超过选课结束时间:'.$course['end_choose_time'],'',400);
        }


        $old = UserTimesModel::where('user_id',$user['id'])
            ->where('course_id',$course_id)
            ->where('teacher_id',$teacher_id)
            ->find();
        if(!empty($old)){
            $this->error('已经选择过此课程了！','',400);
        }

        $old2 = UserTimesModel::where('user_id',$user['id'])->find();
        if(!empty($old2)){
            $this->error('已经选择过其它课程了！','',400);
        }

        $has_count = UserTimesModel::where('course_id',$course_id)->count();//已报名人数
        if($course['sign_total']<=$has_count){
            $this->error('该课程人数已满，不可报名！','',400);
        }
        if (!$this->getAddUserTimeLock($course_id)){
            $this->error('服务器拥挤，请重试','',400);
        }

        // 启动事务
        Db::startTrans();
        try{
            $user_time = UserTimesModel::create([
                'user_id'=>$user['id'],
                'course_id'=>$course_id,
                'teacher_id'=>$teacher_id,
                'time'=>$time,
                'create_time'=>date('Y-m-d H:i:s')
            ]);
            CourseModel::where('id',$course_id)->setInc('sign_count');
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $user_time = null;
        }

        $this->releaseLock($course_id);
        if(!empty($user_time)){
            $this->success('选课成功！',$user_time);
        }else{
            $this->error('选课失败,请刷新重试！','',400);
        }
    }

    protected function getAddUserTimeLock($course_id){
        $LOCK_NAME = 'course'.$course_id;

        $lock = cache($LOCK_NAME);

        if(empty($lock)){
            cache($LOCK_NAME,1,300);
            return true;
        }

        return false;
    }

    protected function updateAddUserTimeLock($course_id){
        $LOCK_NAME = 'course'.$course_id;
        cache($LOCK_NAME,1,300);
    }

    protected function releaseLock($course_id){
        $LOCK_NAME = 'course'.$course_id;
        cache($LOCK_NAME,NULL);
    }


    public function _add_user_time_form_filter(&$data)
    {
        if ($this->request->isPost()) {
            $course = CourseModel::where('id',$data['id'])->find();
            CourseModel::where('id',$data['id'])->setInc('sign_count');
            $has = UserTimesModel::where([
                "user_id"=>$data['user_id'],
                "course_id"=>$data['id'],
            ])->find();
            if(empty($has)){
                UserTimesModel::create([
                    "user_id"=>$data['user_id'],
                    "course_id"=>$data['id'],
                    "teacher_id"=>$course['teacher_id'],
                    "time"=>$course['time'],
                ]);
            }
        }
    }

    /**
     * 批量添加报名
     */
    public function add_user_time_more()
    {
        if($this->request->isPost()){
            $data = input();
            if (!$this->getAddUserTimeLock($data['id'])){
                $this->error('服务器拥挤，请重试','',400);
            }
            $course = CourseModel::where('id',$data['id'])->find();
            $user_names_arr = explode("\r\n", trim($data['user_names']));

            $ret = [];
            foreach ($user_names_arr as $key=>$value){
                //找到学生id
                $user_id = UserModel::where('realname',$value)->value('id');

                if ($this->add_user_time_list($user_id,$data['id'],$course) === true){
                    $msg = $value.'_成功';
                }else{
                    $msg = $value.'_失败';
                }

                $ret[] = $msg;
                $this->updateAddUserTimeLock($data['id']);  //续锁时间
            }
            $this->releaseLock($data['id']);
            $this->success('处理完毕！！',$ret);
        }else{
            $this->title = '批量添加报名此课程';
            return $this->_form($this->model, 'user_times_more');
        }
    }

    public function add_user_time_list($user_id,$id,$course){


        Db::startTrans();
        try{
            $user = UserModel::get($user_id);
            if(empty($user['realname'])){
                $this->error('真实姓名未填，请去个人中心修改信息','',400);
            }
            $course_id = $id;

            $teacher_id = $course['teacher_id'];
            $time = $course['time'];
            if(!empty($course['school_id']) && $course['school_id']!=$user['school_id']){
                $this->error('学生绑定学校不符','',400);
            }
            if(!empty($course['begin_choose_time'])&&time()<strtotime($course['begin_choose_time'])){
                $this->error('未到选课开始时间:'.$course['begin_choose_time'],'',400);
            }
            if(!empty($course['end_choose_time'])&&time()>strtotime($course['end_choose_time'])){
                $this->error('已超过选课结束时间:'.$course['end_choose_time'],'',400);
            }
            $old = UserTimesModel::where('user_id',$user['id'])
                ->where('course_id',$course_id)
                ->where('teacher_id',$teacher_id)
                ->find();
            if(!empty($old)){
                $this->error('已经选择过此课程了！','',400);
            }
            $old2 = UserTimesModel::where('user_id',$user['id'])->find();
            if(!empty($old2)){
                $this->error('已经选择过其它课程了！','',400);
            }
            $has_count = UserTimesModel::where('course_id',$course_id)->count();//已报名人数
            if($course['sign_total']<=$has_count){
                $this->error('该课程人数已满，不可报名！','',400);
            }
            $user_time = UserTimesModel::create([
                'user_id'=>$user['id'],
                'course_id'=>$course_id,
                'teacher_id'=>$teacher_id,
                'time'=>$time,
                'create_time'=>date('Y-m-d H:i:s')
            ]);
            CourseModel::where('id',$course_id)->setInc('sign_count');
            // 提交事务
            Db::commit();
            return true;
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $e->getMessage();
        }

    }

    public function _add_user_time_more_form_filter(&$data)
    {
        if ($this->request->isPost()) {
            $course = CourseModel::where('id',$data['id'])->find();
            $user_names_arr = explode("\r\n", trim($data['user_names']));
            foreach ($user_names_arr as $key=>$value){
                //找到学生id
                $user_id = UserModel::where('realname',$value)->value('id');
                if(!empty($user_id)){
                    $has = UserTimesModel::where([
                        "user_id"=>$user_id,
                        "course_id"=>$data['id'],
                    ])->find();
                    //查看是否已报名
                    if(empty($has)){
                        UserTimesModel::create([
                            "user_id"=>$user_id,
                            "course_id"=>$data['id'],
                            "teacher_id"=>$course['teacher_id'],
                            "time"=>$course['time'],
                        ]);
                        CourseModel::where('id',$data['id'])->setInc('sign_count');
                    }
                }
            }
        }
    }

    /**
     * 删除
     */
    public function delete_user_time()
    {
        $this->title = '删除学生报名此课程';
        return $this->_form($this->model, 'user_times');
    }

    public function _delete_user_time_form_filter(&$data)
    {
        if ($this->request->isPost()) {
            CourseModel::where('id',$data['id'])->setDec('sign_count');
            UserTimesModel::where([
                "user_id"=>$data['user_id'],
                "course_id"=>$data['id'],
            ])->delete();
        }
    }

    /**
     * 编辑
     */
    public function edit(){
        $this->title = '编辑';
//        dump($this->model->with(['logs'])->append(['specs','product'])->select());die;
//        $this->model->setQuery($this->model->with(['logs'])->append(['specs','product']));
        return $this->_form($this->model,'form');
    }

    public function _edit_form_filter(&$data)
    {
        if ($this->request->isPost()) {
            $this->alterInfo($data);
        }
    }

//    protected function _edit_form_result($result,$data)
//    {
//        if ($result && $this->request->isPost()) {
//             Db::table('huilife_goods_product')
//                ->where('goods_id',$data['id'])
//                ->delete();
//             Db::table('huilife_goods_specs')
//                ->where('goods_id',$data['id'])
//                ->delete();
//
//            foreach ($data['product'] as $key=>$value){
//                //规格库存价格表
//                GoodsProductModel::create([
//                    'goods_id' =>$data['id'],
//                    'goods_sn' =>$data['id'].'-'.$key,
//                    'market_price' =>$value['market_price'],
//                    'price' =>$value['price'],
//                    'stock' =>$value['stock'],
//                    'spec' =>$value['goods_spec'],
//                ]);
//            }
//
//            foreach (json_decode($data['specs']['spec_list'],true) as $key1=>$value1){
//                foreach ($value1['list'] as $key2=>$value2){
//                    //规格名称表
//                    GoodsSpecsModel::create([
//                        'goods_id' =>$data['id'],
//                        'spec_name' =>$value1['name'],
//                        'name' =>$value2['name'],
//                        'image' =>$value2['image'],
//                    ]);
//                }
//            }
//            $this->success('商品编辑成功！', 'javascript:history.back()');
//        }
//    }

    protected function alterInfo(&$data){

        if(!isset($data['logo']) || empty($data['logo'])){
            $this->error('请上传课程图');
        }

        if(!isset($data['intro']) || empty($data['intro'])){
            $this->error('请上传详情图');
        }
        $data['type'] = 2;
    }

    /**
     * 删除
     */
    public function del()
    {
        $this->_delete($this->model);
    }

    /**
     * 启用/关闭
     */
    public function upstatus(){
        $this->_save($this->model, [
            'status' => $this->request->request('status'),
        ],'id', ['id' => $this->request->request('id')]);
    }
    
    /**
     * 启用/关闭
     */
    public function upishot(){
        $this->_save($this->model, [
            'is_hot' => $this->request->request('is_hot'),
        ],'id', ['id' => $this->request->request('id')]);
    }

    /**
     * 课程导入
     */
    public function import()
    {
        require(dirname(__FILE__) . '/../../../vendor/spreadsheet/php-excel-reader/excel_reader2.php');
        require(dirname(__FILE__) . '/../../../vendor/spreadsheet/SpreadsheetReader.php');
        $file = $this->request->file('file');
        if (empty($file)) {
            $this->error('未上传文件');
        }else {
            $upload = array(
                'uploadurl' => 'ajax/upload',
                'cdnurl'    => '',
                'savekey'   => '/upload/excel/{filemd5}{.suffix}',
                'maxsize'   => '1024mb',
                'mimetype'  => 'xls,xlsx',
                'multiple'  => false
            );

            preg_match('/(\d+)(\w+)/', $upload['maxsize'], $matches);
            $type = strtolower($matches[2]);
            $typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
            $size = (int)$upload['maxsize'] * pow(999999, isset($typeDict[$type]) ? $typeDict[$type] : 0);
            $fileInfo = $file->getInfo();
            $suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
            $suffix = $suffix ? $suffix : 'file';

            $mimetypeArr = explode(',', strtolower($upload['mimetype']));
            $typeArr = explode('/', $fileInfo['type']);

            //验证文件后缀
            if ($upload['mimetype'] !== '*' &&
                (
                    !in_array($suffix, $mimetypeArr)
                    || (stripos($typeArr[0] . '/', $upload['mimetype']) !== false && (!in_array($fileInfo['type'], $mimetypeArr) && !in_array($typeArr[0] . '/*', $mimetypeArr)))
                )
            ) {
                $this->error('只能上传xls,xlsx文件');
            }
            $replaceArr = [
                '{year}'     => date("Y"),
                '{mon}'      => date("m"),
                '{day}'      => date("d"),
                '{hour}'     => date("H"),
                '{min}'      => date("i"),
                '{sec}'      => date("s"),
                '{filename}' => $suffix ? substr($fileInfo['name'], 0, strripos($fileInfo['name'], '.')) : $fileInfo['name'],
                '{suffix}'   => $suffix,
                '{.suffix}'  => $suffix ? '.' . $suffix : '',
                '{filemd5}'  => md5_file($fileInfo['tmp_name']),
            ];
            $savekey = $upload['savekey'];
            $savekey = str_replace(array_keys($replaceArr), array_values($replaceArr), $savekey);

            $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
            $fileName = substr($savekey, strripos($savekey, '/') + 1);
            $splInfo = $file->move( config('app.file_storage_path') . $uploadDir, $fileName);
            $file = config('app.file_storage_path') . $uploadDir. $fileName;
            $Reader = new \SpreadsheetReader($file);
            foreach ($Reader as $Key => $Row) {
                if ($Key != 1 && !empty($Row)) {
                    $name = $Row[1]; //学校名
                    if ($name != '') {
                        //找到分类id
                        $cate_id = CourseCateModel::where('name',$Row[0])->value('id');
                        $school_id = SchoolModel::where('name',$Row[1])->value('id');
                        $grade_id = SchoolGradeModel::where('name',$Row[2])->value('id');
                        $class_id = SchoolClassModel::where('name',$Row[3])->value('id');
                        $teacher_id = UserModel::where('role',2)->where('realname',$Row[4])->value('id');
                        $name = isset($Row[5])?$Row[5]:''; //课程名称
                        $title = isset($Row[6])?$Row[6]:''; //课程标题
                        $time = isset($Row[7])?$Row[7]:''; //上课时间
                        $address = isset($Row[8])?$Row[8]:''; //上课地点
                        $sign_total = isset($Row[9])?$Row[9]:''; //可报名总人数

                        CourseModel::create([
                            'type'=>2,
                            'cate_id'=>$cate_id,
                            'school_id'=>$school_id,
                            'grade_id'=>$grade_id,
                            'class_id'=>$class_id,
                            'teacher_id'=>$teacher_id,
                            'name'=>$name,
                            'title'=>$title,
                            'time'=>$time,
                            'address'=>$address,
                            'sign_total'=>$sign_total,
                        ]);
                    }
                }
            }
            $this->success('导入成功，课程已更新！');
        }
    }

    /**
     * 课程导入模板
     */
    public function import_template()
    {
        $list[0] = [
            'cate_name'=>'示例请删除 语文',
            'school'=>'深圳实验学校',
            'grade'=>'高中一年级',
            'class'=>'一班',
            'teacher'=>'林辉煌',
            'name'=>'语文',
            'title'=>'语文课',
            'time'=>'每周四 10:00-12:00',
            'address'=>'主教学楼501',
            'sign_total'=>'99'
        ];
        $table_field = [
            ['A' ,'cate_name', '课程分类'],
            ['B' ,'school','学校'],
            ['C' ,'grade','年级'],
            ['D' ,'class', '班级'],
            ['E' ,'teacher', '授课教师'],
            ['F' ,'name','课程名称'],
            ['G' ,'title','课程标题'],
            ['H' ,'time','上课时间'],
            ['I' ,'address','上课地点'],
            ['J' ,'sign_total','可报名总人数'],
        ];
        return $this->_export($list, $table_field, '课程导入模板');
    }

    /**
     * 查看考勤
     */
    public function attendance(){
        $this->title = '查看考勤';
        $course_id = $this->request->get('id');
        $attendance = CourseAttendanceModel::where('course_id',$course_id)
            ->where('day','neq',null)
            ->order('day asc')
            ->select();
        //找到这个课程学生
        $attendance_all_userids = CourseAttendanceModel::where('course_id',$course_id)
            ->where('day','neq',null)
            ->value('all_userids');
        $attendance_all_userids = explode(',',$attendance_all_userids);
        $attendance_student_arr = array();
        foreach ($attendance_all_userids as $key=>$value){
            $attendance_student_arr[$value]['name'] = UserModel::where('id',$value)->value('realname');

            foreach ($attendance as $k1=>$v1){
                if(strpos($v1['in_userids'],$value) !== false){
                    $attendance_student_arr[$value][$v1['day']] = '√';
                }else{
                    $attendance_student_arr[$value][$v1['day']] = '×';
                }
            }
        }
        $this->assign('attendance',$attendance);
        $this->assign('attendance_student_arr',$attendance_student_arr);
        return $this->_form($this->model,'attendance');
    }

    /**
     * 课程导出
     */
    public function export_course()
    {
        $list = CourseModel::where('type',2)
            ->where(function ($db){
                if($this->request->has('name','get') && !empty($this->request->get('name'))){
                    $name = $this->request->get('name');
                    $db->where('name','like','%'.$name.'%');
                }
                if($this->request->has('title','get') && !empty($this->request->get('title'))){
                    $title = $this->request->get('title');
                    $db->where('title','like','%'.$title.'%');
                }
                if($this->request->has('status','get') && !empty($this->request->get('status'))){
                    $status = $this->request->get('status');
                    $db->where('status', $status);
                }
                if($this->request->has('cate_id','get') && !empty($this->request->get('cate_id'))){
                    $cate_id = $this->request->get('cate_id');
                    $db->where('cate_id', $cate_id);
                }
            })
            ->with(['coursecate','school','schoolgrade','schoolclass','teacher'])
            ->order('id desc')
            ->select();
        foreach ($list as $key=>$value){
            $value['cate_name'] = CourseCateModel::where('id',$value['cate_id'])->value('name');
            $value['school'] = SchoolModel::where('id',$value['school_id'])->value('name');
            $value['grade'] = SchoolGradeModel::where('id',$value['grade_id'])->value('name');
            $value['class'] = SchoolClassModel::where('id',$value['class_id'])->value('name');
            $value['teacher'] = UserModel::where('id',$value['teacher_id'])->value('realname');
        }
        $table_field = [
            ['A' ,'cate_name', '课程分类'],
            ['B' ,'school','学校'],
            ['C' ,'grade','年级'],
            ['D' ,'class', '班级'],
            ['E' ,'teacher', '授课教师'],
            ['F' ,'name','课程名称'],
            ['G' ,'title','课程标题'],
            ['H' ,'time','上课时间'],
            ['I' ,'address','上课地点'],
            ['J' ,'sign_count','已报名总人数'],
            ['K' ,'sign_total','可报名总人数'],
        ];

        return $this->_export($list, $table_field, "兴趣课程表");
    }

    /**
     * 考勤记录导出
     */
    public function export_attendance()
    {
        $course_id = $this->request->get('id');
        $attendance = CourseAttendanceModel::where('course_id',$course_id)
            ->where('day','neq',null)
            ->order('day asc')
            ->select();
        //找到这个课程学生
        $attendance_all_userids = CourseAttendanceModel::where('course_id',$course_id)
            ->where('day','neq',null)
            ->value('all_userids');
        $attendance_all_userids = explode(',',$attendance_all_userids);
        $attendance_student_arr = array();
        foreach ($attendance_all_userids as $key=>$value){
            $attendance_student_arr[$value]['name'] = UserModel::where('id',$value)->value('realname');
            $attendance_student_arr[$value]['school_name'] = UserModel::where('id',$value)->value('school_name');
            $attendance_student_arr[$value]['grade_name'] = SchoolGradeModel::where('id',UserModel::where('id',$value)->value('grade_id'))->value('name');
            $attendance_student_arr[$value]['class_name'] = SchoolClassModel::where('id',UserModel::where('id',$value)->value('class_id'))->value('name');

            foreach ($attendance as $k1=>$v1){
                if(strpos($v1['all_userids'],$value) !== false){
                    $attendance_student_arr[$value][$v1['day']] = '√';
                }else{
                    $attendance_student_arr[$value][$v1['day']] = '×';
                }
            }
        }

        $table_field = [
            ['A' ,'name', '学生姓名'],
            ['B' ,'school_name', '学校'],
            ['C' ,'grade_name', '年级'],
            ['D' ,'class_name', '班级'],
        ];
        foreach ($attendance as $k2=>$v2){
            if(isset($k2)&&$k2==0){
                array_push($table_field,['E',$v2['day'],$v2['day']]);
            }
            if(isset($k2)&&$k2==1){
                array_push($table_field,['F',$v2['day'],$v2['day']]);
            }
            if(isset($k2)&&$k2==2){
                array_push($table_field,['G',$v2['day'],$v2['day']]);
            }
            if(isset($k2)&&$k2==3){
                array_push($table_field,['H',$v2['day'],$v2['day']]);
            }
            if(isset($k2)&&$k2==4){
                array_push($table_field,['I',$v2['day'],$v2['day']]);
            }
            if(isset($k2)&&$k2==5){
                array_push($table_field,['J',$v2['day'],$v2['day']]);
            }
            if(isset($k2)&&$k2==6){
                array_push($table_field,['K',$v2['day'],$v2['day']]);
            }
            if(isset($k2)&&$k2==7){
                array_push($table_field,['L',$v2['day'],$v2['day']]);
            }
            if(isset($k2)&&$k2==8){
                array_push($table_field,['M',$v2['day'],$v2['day']]);
            }
            if(isset($k2)&&$k2==9){
                array_push($table_field,['N',$v2['day'],$v2['day']]);
            }
            if(isset($k2)&&$k2==10){
                array_push($table_field,['O',$v2['day'],$v2['day']]);
            }
            if(isset($k2)&&$k2==11){
                array_push($table_field,['P',$v2['day'],$v2['day']]);
            }
            if(isset($k2)&&$k2==12){
                array_push($table_field,['Q',$v2['day'],$v2['day']]);
            }
            if(isset($k2)&&$k2==13){
                array_push($table_field,['R',$v2['day'],$v2['day']]);
            }
            if(isset($k2)&&$k2==14){
                array_push($table_field,['S',$v2['day'],$v2['day']]);
            }
            if(isset($k2)&&$k2==15){
                array_push($table_field,['T',$v2['day'],$v2['day']]);
            }
            if(isset($k2)&&$k2==16){
                array_push($table_field,['U',$v2['day'],$v2['day']]);
            }
            if(isset($k2)&&$k2==17){
                array_push($table_field,['V',$v2['day'],$v2['day']]);
            }
            if(isset($k2)&&$k2==18){
                array_push($table_field,['W',$v2['day'],$v2['day']]);
            }
            if(isset($k2)&&$k2==19){
                array_push($table_field,['X',$v2['day'],$v2['day']]);
            }
            if(isset($k2)&&$k2==20){
                array_push($table_field,['Y',$v2['day'],$v2['day']]);
            }
            if(isset($k2)&&$k2==21){
                array_push($table_field,['Z',$v2['day'],$v2['day']]);
            }
            if(isset($k2)&&$k2==22){
                array_push($table_field,['AA',$v2['day'],$v2['day']]);
            }
            if(isset($k2)&&$k2==23){
                array_push($table_field,['AB',$v2['day'],$v2['day']]);
            }
            if(isset($k2)&&$k2==24){
                array_push($table_field,['AC',$v2['day'],$v2['day']]);
            }
        }
        $list = array();
        foreach ($attendance_student_arr as $k3=>$v3){
            foreach ($v3 as $k4=>$v4){
                $list[$k3][$k4] = $v4;
            }
        }
        $list = array_values($list);
        $course_name = CourseModel::where('id',$course_id)->value('name');
        return $this->_export($list, $table_field, "课程".$course_name."的考勤记录");
    }

    /**
     * 查看已报名学生
     */
    public function baoming(){
        $this->title = '查看已报名学生';
        $course_id = $this->request->get('id');
        $user_ids = UserTimesModel::where('course_id',$course_id)->select();
        $student = [];
        foreach ($user_ids as $key=>$value){
            //找到这个课程学生
            $user = UserModel::where('id',$value['user_id'])->find();
            $student[$key]['id'] = $user['id'];
            $student[$key]['realname'] = $user['realname'];
            $student[$key]['phone'] = $user['phone'];
            $student[$key]['student_no'] = $user['student_no'];
            $student[$key]['grade_name'] = SchoolGradeModel::where('id',$user['grade_id'])->value('name');
            $student[$key]['class_name'] = SchoolClassModel::where('id',$user['class_id'])->value('name');
        }
        $this->assign('student_count',count($user_ids));
        $this->assign('student',$student);
        return $this->_form($this->model,'baoming');
    }


    /**
     * 导出已报名学生
     */
    public function export_baoming_form()
    {
        return $this->_form($this->model, 'export_baoming_form');
    }

    /**
     * 导出已报名学生
     */
    public function export_baoming()
    {
        $user_ids = UserTimesModel::where(function ($db){
            if($this->request->has('course_id','get') && !empty($this->request->get('course_id'))){
                $course_id = $this->request->get('course_id');
                $db->where('course_id', $course_id);
            }
        })->all();


        $student = [];
        foreach ($user_ids as $key=>$value) {
            //找到这个课程学生
            $user = UserModel::where('id',$value['user_id'])->find();

            if($this->request->has('class_id','get') && !empty($this->request->get('class_id')) && $this->request->get('class_id') != $user['class_id']){
                continue;
            }

            $temp = [];
            $temp['id'] = $user['id'];
            $temp['realname'] = $user['realname'];
            $temp['grade_name'] = SchoolGradeModel::where('id',$user['grade_id'])->value('name');
            $temp['class_name'] = SchoolClassModel::where('id',$user['class_id'])->value('name');
            $student[] = $temp;
        }

        $table_field = [
            ['A' ,'realname', '姓名'],
            ['B' ,'grade_name','年级'],
            ['C' ,'class_name','班级'],
        ];

        return $this->_export($student, $table_field, "已报名学生");

    }
}
